package com.tanhua.dubbo.api;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mapper.UserInfoMapper;
import com.tanhua.model.domain.UserInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户基础信息的dubbo实现类
 */
@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    //根据id查询
    @Override
    public UserInfo findById(Long id) {

        return userInfoMapper.selectById(id);
    }

    //更新
    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    //保存
    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    //根据ids查询用户列表详情
    @Override
    public Map<Long, UserInfo> findByIds(List<Long> ids, UserInfo info) {
        LambdaQueryWrapper<UserInfo> qw = new LambdaQueryWrapper<>();
        //1.用户id列表
        qw.in(UserInfo::getId, ids);
        //2.添加筛选条件
        if (info != null) {
            if (info.getAge() != null) {
                qw.lt(UserInfo::getAge, info.getAge());
            }
            if (!StringUtils.isEmpty(info.getGender())) {
                qw.eq(UserInfo::getGender, info.getGender());
            }
            if (!StringUtils.isEmpty(info.getNickname())) {
                qw.like(UserInfo::getNickname, info.getNickname());
            }
        }
        //调用mapper查询得到list集合
        List<UserInfo> list = userInfoMapper.selectList(qw);
        //转为map返回 id为主键 本体为值
        Map<Long, UserInfo> map = list.parallelStream().
                collect(Collectors.toMap(UserInfo::getId, Function.identity()));
        return map;
    }

    //分页查询用户信息
    @Override
    public Page<UserInfo> findAllUsers(Integer page, Integer pagesize) {
        //根据page,pagesize查询所有信息, --wrapper为null
        Page<UserInfo> pageInfo=new Page<>(page,pagesize);
        Page<UserInfo> userInfoIPage = userInfoMapper.selectPage(pageInfo, null);
        return userInfoIPage;
    }
}